<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/25 0025
 * Time: 17:46
 */

////////////////////////// 用户信息 模块 start
use HiCommon\Repository\EntrustRoleUserRepository;
use HiCommon\Repository\ShopRepository;


/**
 * admin 模块-判断用户是否是超级用户admin
 *
 * @return bool
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function is_admin_super()
{
    if(admin_user_id() == 1)
    {
        return true;
    }

    return false;

}

/**
 * 获取权限缓存key
 *
 * @param string $s_model
 *
 * @return string
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function permission_cache_key($s_model = ''){
    $key = 'permission_cache';
    if(!empty($s_model)){
        $key = 'permission_cache_'.$s_model;
    }
    return $key;
}

function permission_redis_db(){
    return 2;
}


/**
 * 获取权限缓存
 *
 * @param string $key
 *
 * @return array|mixed|string
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function cache_permission($key = 'all')
{
    $n_db = permission_redis_db();
    $s_table = 'permission';
    $s_redis_key = $key;
    $result = predis_hash_get($s_table,$s_redis_key,$n_db);
    $arr_where = [];
    if (is_null($result)) {
        if ($key !== 'all'){
            $arr_where['model'] = $key;
        }
        $result = \HiCommon\Repository\EntrustPermissionsRepository::normal_all_where_sort($arr_where)
                                                                ->toarray();
        predis_hash_set($s_table,$s_redis_key,$result,$n_db);
    }
    return $result;
}

/*获取权限缓存-管理后台*/
function cache_permission_for_admin(){
    return cache_permission('admin');
}

/*获取权限缓存-商户后台-检测机构*/
function cache_permission_for_shop_check(){
    return cache_permission('shop_check');
}

/*获取权限缓存-商户端APP-检测机构*/
function cache_permission_for_shop_check_app(){
    return cache_permission('shop_check_app');
}

/*获取权限缓存-商户后台-维修店*/
function cache_permission_for_shop_repair(){
    return cache_permission('shop_repair');
}

/*获取权限缓存-商户端APP-维修店*/
function cache_permission_for_shop_repair_app(){
    return cache_permission('shop_repair_app');
}

/*获取权限缓存-商户后台-道路救援*/
function cache_permission_for_shop_roadhelp(){
    return cache_permission('shop_roadhelp');
}

/*清除所有缓存 = 权限缓存+菜单缓存+用户权限缓存(权限设置修改时，进行此操作)*/
function clear_cache_for_all(){
    clear_cache_hash_permission();//清除权限缓存
    clear_cache_for_admin();//清除管理用户缓存 = 菜单+权限
    clear_cache_for_shop();//清除商户用户缓存 = 菜单+权限



}

/*清除管理用户缓存 = 菜单+权限*/
function clear_cache_for_admin(){
    clear_cache_hash_user_permission_for_admin();//清除管理用户-权限缓存
    clear_cache_hash_user_html_menu_for_admin();//清除管理用户-菜单缓存
}

/*清除商户用户缓存 = 菜单+权限*/
function clear_cache_for_shop(){
    clear_cache_hash_user_permission_for_shop();//清除商户后台用户-权限缓存
    clear_cache_hash_user_html_menu_for_shop();//清除商户后台用户-菜单缓存
    clear_cache_hash_user_permission_for_shop_app();//清除商户APP用户-权限缓存

}

/*清除hash缓存*/
function clear_cache_hash($s_table){
    $n_db = permission_redis_db();
    $result = predis_hash_del_all($s_table,$n_db);
    return $result;
}

/*清除hash的key缓存*/
function clear_cache_hash_key($s_table,$s_key){
    $n_db = permission_redis_db();
    $result = predis_hash_del($s_table,$s_key,$n_db);
    return $result;
}

/*清除权限缓存*/
function clear_cache_hash_permission(){
    $result = clear_cache_hash('permission');
    return $result;
}

/*清除权限缓存-管理后台用户 */
function clear_cache_hash_user_permission_for_admin($n_uid = 0){
    $n_uid = intval($n_uid);
    $table = 'user_permission_for_admin';
    $key = 'uid:'.$n_uid;
    if($n_uid === 0){
        $result = clear_cache_hash($table);
    }
    else{
        $result = clear_cache_hash_key($table,$key);
    }
    return $result;
}

/*清除权限缓存-商户后台用户 */
function clear_cache_hash_user_permission_for_shop($n_uid = 0){
    $n_uid = intval($n_uid);
    $table = 'user_permission_for_shop';
    $key = 'uid:'.$n_uid;
    if($n_uid === 0){
        $result = clear_cache_hash($table);
    }
    else{
        $result = clear_cache_hash_key($table,$key);
    }
    return $result;
}

/*清除权限缓存-清除商户APP用户 */
function clear_cache_hash_user_permission_for_shop_app($n_uid = 0){
    $n_uid = intval($n_uid);
    $table = 'user_permission_for_shop_app';
    $key = 'uid:'.$n_uid;
    if($n_uid === 0){
        $result = clear_cache_hash($table);
    }
    else{
        $result = clear_cache_hash_key($table,$key);
    }
    return $result;
}

/*清除菜单html缓存-管理后台用户 */
function clear_cache_hash_user_html_menu_for_admin($n_uid = 0){
    $n_uid = intval($n_uid);
    $table = 'user_html_menu_for_admin';
    $key = 'uid:'.$n_uid;
    if($n_uid === 0){
        $result = clear_cache_hash($table);
    }
    else{
        $result = clear_cache_hash_key($table,$key);
    }
    return $result;
}

/*清除菜单html缓存-商户后台用户 */
function clear_cache_hash_user_html_menu_for_shop($n_uid = 0){
    $n_uid = intval($n_uid);
    $table = 'user_html_menu_for_shop';
    $key = 'uid:'.$n_uid;
    if($n_uid === 0){
        $result = clear_cache_hash($table);
    }
    else{
        $result = clear_cache_hash_key($table,$key);
    }
    return $result;
}

/**
 * 获取ztree权限
 *
 *
 * @return mixed
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function ztree_permissions()
{
    $result = cache_permission();
    $result = collect($result)->map(function ($value,$key){
    if($value['is_menu'] == 1){
        //                $value['iconOpen'] = "/admin/lib/zTree/css/zTreeStyle/img/diy/1_open.png";
        //                $value['iconClose'] = "/admin/lib/zTree/css/zTreeStyle/img/diy/1_close.png";
        if($value['status'] == 1){
            $value['icon'] = "/admin/lib/zTree/css/zTreeStyle/img/diy/menu.png";
        }
        else{
            $value['icon'] = "/admin/lib/zTree/css/zTreeStyle/img/diy/menu_disabled.png";
        }
    }
    else{
        if($value['status'] == 1){
            $value['icon'] = "/admin/lib/zTree/css/zTreeStyle/img/diy/point.png";
        }
        else{
            $value['icon'] = "/admin/lib/zTree/css/zTreeStyle/img/diy/point_disabled.png";
        }
    }
    $value['real_name'] = $value['name'];
    $value['name'] = $value['name'].'<-->'.$value['route'];
    return $value;
    //            return collect($value)->only(['id','route','alias','name','pid','sort'])->toArray();
})->all();
    return $result;
}

/**
 * 根据用户id获取管理后台权限缓存
 *
 * @param $n_uid
 *
 * @return mixed
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function cache_user_permissions_for_admin($n_uid){
    $db = permission_redis_db();
    $table = 'user_permission_for_admin';
    $key = 'uid:'.$n_uid;

    //取缓存数据
    $result = predis_hash_get($table,$key,$db);
    if (is_null($result)) {

        //更新缓存数据
        $arr_all_permissions = cache_permission_for_admin();
        if($n_uid == 1){
            /*超级管理员admin账号查询所有权限*/
            $result = $arr_all_permissions;
        }
        else{
            /*其他账号查询分配的权限*/
            //            $arr_result = self::get_user_permissions_admin($arr_all_permissions,$n_uid);
            $arr_admin_user_permission_ids = \HiCommon\Repository\EntrustPermissionRoleRepository::get_admin_all_by_uid($n_uid)->pluck('permission_id')->all();
            $result = collect($arr_all_permissions)->whereIn('id',$arr_admin_user_permission_ids)->values()->all();
        }

        predis_hash_set($table,$key,$result,$db);
    }
    return $result;
}

/**
 * 根据用户id获取商户后台权限缓存
 *
 * @param $n_uid
 *
 * @return mixed
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function cache_user_permissions_for_shop($n_uid){
    $db = permission_redis_db();
    $table = 'user_permission_for_shop';
    $key = 'uid:'.$n_uid;

    //取缓存数据
    $result = predis_hash_get($table,$key,$db);
    if (is_null($result)) {

        //更新缓存数据
        $arr_shop_user = \HiCommon\Repository\ShopUserRepository::find_one_login($n_uid)->toarray();
        $n_is_master = $arr_shop_user['is_master'];
        if($arr_shop_user['shop_base']['cate'] == 1){
            //        $s_model = 'shop_check';
            $arr_all_permissions_shop = cache_permission_for_shop_check();

        }
        elseif($arr_shop_user['shop_base']['cate'] == 2){
            //        $s_model = 'shop_repair';
            $arr_all_permissions_shop = cache_permission_for_shop_repair();

        }
        elseif($arr_shop_user['shop_base']['cate'] == 3){
            //        $s_model = 'shop_roadhelp';
            $arr_all_permissions_shop = cache_permission_for_shop_roadhelp();

        }
        if($n_is_master == 1){
            /*主账号查询所有权限*/
            $result = $arr_all_permissions_shop;
        }
        else{
            /*子账号查询分配的权限*/
            $arr_admin_user_permission_ids = \HiCommon\Repository\EntrustPermissionRoleRepository::get_shop_all_by_uid($n_uid)->pluck('permission_id')->all();
            $result = collect($arr_all_permissions_shop)->whereIn('id',$arr_admin_user_permission_ids)->values()->all();
        }
        predis_hash_set($table,$key,$result,$db);
    }
    return $result;
}

/**
 * 根据用户id获取商户APP权限缓存
 *
 * @param $n_uid
 *
 * @return mixed
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function cache_user_permissions_for_shop_app($n_uid){
    $db = permission_redis_db();
    $table = 'user_permission_for_shop_app';
    $key = 'uid:'.$n_uid;

    //取缓存数据
    $result = predis_hash_get($table,$key,$db);
    if (is_null($result)) {

        //更新缓存数据
        $arr_shop_user = \HiCommon\Repository\ShopUserRepository::find_one_login($n_uid)->toarray();
        $n_is_master = $arr_shop_user['is_master'];
        if($arr_shop_user['shop_base']['cate'] == 1){
            //        $s_model = 'shop_check';
            $arr_all_permissions_shop = cache_permission_for_shop_check_app();

        }
        elseif($arr_shop_user['shop_base']['cate'] == 2){
            //        $s_model = 'shop_repair';
            $arr_all_permissions_shop = cache_permission_for_shop_repair_app();

        }
        if($n_is_master == 1){
            /*主账号查询所有权限*/
            $result = $arr_all_permissions_shop;
        }
        else{
            /*子账号查询分配的权限*/
            $arr_admin_user_permission_ids = \HiCommon\Repository\EntrustPermissionRoleRepository::get_shop_all_by_uid($n_uid)->pluck('permission_id')->all();
            $result = collect($arr_all_permissions_shop)->whereIn('id',$arr_admin_user_permission_ids)->values()->all();
        }
        predis_hash_set($table,$key,$result,$db);
    }
    return $result;
}



//function permission_cache_for_user($n_uid = 0,$s_model = ''){
//    $table = 'permission_cache_'.$s_model;
//    $key = $s_model.':'.$n_uid;
//    $result = predis_hash_get($table,$key,2);
//    if (is_null($result)) {
//        $result = permission_cache_for_user_refresh($n_uid,$s_model);
//    }
//    return $result;
//}
//
//function permission_cache_for_user_refresh($n_uid,$s_model){
//
//}

///**
// * 获取权限缓存-根据后台用户id
// *
// * @return mixed
// * @author wumengmeng <wu_mengmeng@foxmail.com>
// */
//function get_permission_cache_by_uid($n_admin_id){
//    $res = Cache::get('permission_cache:'.$n_admin_id);
//    if(is_null($res)){
//        $res = permission_cache_refresh_by_uid($n_admin_id);
//    }
//    return $res;
//}
//
///**
// * 刷新权限缓存-根据后台用户id
// *
// * @return mixed
// * @author wumengmeng <wu_mengmeng@foxmail.com>
// */
//function permission_cache_refresh_by_uid($n_admin_id){
//    $arr_permission_ids = \Modules\Admin\Service\MenuService::get_user_permission_ids();
//    $res        = \HiCommon\Repository\EntrustPermissionsRepository::get_permissions_by_ids($arr_permission_ids)->toarray();
//    Cache::forever('permission_cache:'.$n_admin_id,$res);
//    return $res;
//}
////////////////////////// 用户信息 模块 end
///


function go_to_login(){
   return redirect(route('admin_login'));
}


/**
 *  生成（唯一的）优惠券的券号
 *  优惠券类型|当前时间戳的后6位|5位数值随机数
 *  时间戳后6位  每隔12-13天 就会有一次重复值
 **/
function set_coupons_ticket_num( $type = 1 ){
    $str = 'XCQ';
    if( $type == 2 ){
        $str = 'MJQ';
    }else if( $type == 3 ){
        $str = 'ZKQ';
    }
    $time = time();
    $rand = mt_rand(10000,99999);
    return $str.substr( $time, -6).$rand;
}

/**
 * 获取后台管理员角色id
 */
function get_admin_role_id()
{
    $arr_map = ['user_id' => admin_user_id()];
    $arr_option = ['role_id', 'user_id'];
    return EntrustRoleUserRepository::get_one_by_where((array)$arr_map, (array)$arr_option);
}

/**
 * 获取商城门店id
 */
function get_shop_id()
{
    return 1;//管理员默认门店id 为1

    /*$admin_id = admin_guard()->id();
    $store = ShopRepository::get_where_one(['admin_id' => $admin_id]);
    if($store){
        return $store->id;
    }else{
        return null;
    }*/
}

function truncate_for_order_checkpoint(){
    $arr_table = [
      'car_order',
      'car_order_checkpoint',
      'car_order_checkpoint_vehicle',
      'car_users_vehicle',
    ];
    foreach ($arr_table as $value)
    {
        $sql = 'truncate '.$value.';';
        DB::delete($sql);
    }

}



//年检预约订单-订单号
function order_sn_njyy(){
    return random_order_sn('NJYY');
}

//年检预约订单-车辆-订单号
function order_sn_njcl(){
    return random_order_sn('NJCL');
}

//年检预约订单-车辆-代驾-订单号
function order_sn_njdj(){
    return random_order_sn('NJDJ');
}

//年检预约订单-退款售后编号
function order_sn_njtk(){
    return random_order_sn('NJTK');
}

/**
 * 资讯类统一分类
 *
 * @return \Illuminate\Config\Repository|mixed
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function common_collect_type_ids()
{
    return arr_value_to_key(config('system.collect_type',[]));
}

/**
 * 导出Excel
 */
function export_excel($cellData = [])
{
    $cellData = [
        ['学号', '姓名', '成绩'],
        ['10001', '12', '99'],
        ['10002', '123', '92'],
        ['10003', '123', '95'],
        ['10004', '123', '89'],
        ['10005', '123', '96'],
    ];
    Excel::create("学生成绩", function ($excel) use ($cellData) {
        $excel->sheet('score', function ($sheet) use ($cellData) {
            $sheet->rows($cellData);
            $sheet->getDefaultStyle()->getFont()->setName('宋体')->setSize(14);
            $sheet->setWidth(array('A' => 8));

            //$sheet->setTitle('订单列表');
            // $sheet->setAutoSize(true);
            // $sheet->mergeCells('A2:B3');//合并单元格
            //$sheet->getStyle('A1')->getFont()->setSize(14)->setBold(true);
            /*  $sheet->getDefaultRowDimension()->setRowHeight(30);
              $sheet->getStyle('B2')->getAlignment()->setVertical('center');
              $sheet->getColumnDimension('B')->setWidth(100);*/
            //$sheet->getStyle('A1')->getFont()->setBold(true);//字体加粗
        });
    })->export('xls');
}

///**
// * 无限属性菜单html
// *
// * @param $arr_menu_list
// *
// * @return string
// * @author wumengmeng <wu_mengmeng@foxmail.com>
// */
//function tree_menu_html($arr_menu_list){
//    $s_html = '';
//    foreach ($arr_menu_list as $value)
//    {
//        $s_header = '';
//        $s_content = '';
//        $s_footer = '';
//        if($value['level'] == 0){
//            $s_header .= ' <li>
//                    <a href="javascript:;">
//                        <i class="iconfont left-nav-li" lay-tips="'.$value['name'].'">'.$value['ico'].'</i>
//                        <cite>'.$value['name'].'</cite>
//                        <i class="iconfont nav_right">&#xe697;</i>
//                    </a>';
//
//
//        }
//        else{
//
//            if(!empty($value['_child'])){
//                $s_header .= '<li>
//                                        <a href="javascript:;">
//                                            <i class="iconfont">&#xe6a7;</i>
//                                            <cite>'.$value['name'].'</cite>
//                                            <i class="iconfont nav_right">&#xe697;</i>
//                                        </a>';
//            }
//            else{
//                $s_header .= '<li>
//                                        <a onclick="xadmin.add_tab(\''.$value['name'].'\',\''.$value['route'].'\')">
//                                            <i class="iconfont">&#xe6a7;</i>
//                                            <cite>'.$value['name'].'</cite></a>';
//            }
//        }
//        if(!empty($value['_child'])){
//            $s_header .= '<ul class="sub-menu">';
//            $s_footer .= '</ul>';
//            $s_content = tree_menu_html($value['_child']);
//
//        }
//        $s_footer .= '</li>';
//
//        $s_html .= $s_header.$s_content.$s_footer;
//
//    }
//    return $s_html;
//}

/**
 * 无限属性菜单html
 *
 * @param $arr_menu_list
 *
 * @return string
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function tree_menu_html($arr_menu_list){
    $s_html = '';
    foreach ($arr_menu_list as $value)
    {
        $s_header = '';
        $s_content = '';
        $s_footer = '';
        if($value['level'] == 0){
            $s_header .= ' <li>
                    <a href="javascript:;">
                        <cite>'.$value['name'].'</cite>
                    </a>';


        }
        else{

            if(!empty($value['_child'])){
                $s_header .= '<li>
                                        <a href="javascript:;">
                                            <i class="iconfont">&#xe6a7;</i>
                                            <cite>'.$value['name'].'</cite>
                                        </a>';
            }
            else{
                $s_header .= '<li>
                                        <a onclick="xadmin.add_tab(\''.$value['name'].'\',\''.$value['route'].'\')">
                                            <i class="iconfont">&#xe6a7;</i>
                                            <cite>'.$value['name'].'</cite></a>';
            }
        }
        if(!empty($value['_child'])){
            $s_header .= '<ul class="sub-menu">';
            $s_footer .= '</ul>';
            $s_content = tree_menu_html($value['_child']);

        }
        $s_footer .= '</li>';

        $s_html .= $s_header.$s_content.$s_footer;

    }
    return $s_html;
}

/**
 * 结算手续费率-redis key
 *
 * @return string
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function redis_key_settle_service_fee_rate(){
    $s_key = 'str_config_settle_service_fee_rate';
    return $s_key;
}

/**
 * 结算手续费率-redis获取
 *
 * @return string
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function redis_settle_service_fee_rate(){
    $s_key = redis_key_settle_service_fee_rate();
    $result = redis_string_get($s_key);
    if(is_null($result)){
        $config_private = \HiCommon\Repository\ConfigPrivateRepository::base_find_one(1);
        if(is_null($config_private)){
            $rate = 0;
        }
        else{
            $rate = $config_private->settle_service_fee_rate;
        }
        $result = number_format($rate,4);
        redis_string_set($s_key,$result);
    }
    return $result;
}

/**
 * 结算手续费率-redis刷新
 *
 * @return string
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function redis_refresh_settle_service_fee_rate(){
    $s_key = redis_key_settle_service_fee_rate();
    $result = redis_string_del($s_key);

    //重新获取结算手续费率
    redis_settle_service_fee_rate();

    return $result;
}

/**************** 消息通知队列 ****************/


/*通知队列-塞入数据*/
function predis_notice_queue_in($data){
    //$data['notice_type'] 通知消息类型 自己定义

    $json_data = json_encode($data);

    $table = 'notice';
    $result = predis_queue_in($table,$json_data);
    return $result;
}

/*通知队列-取出数据*/
function predis_notice_queue_out(){
    $table = 'notice';
    $result = predis_queue_out($table,10);
    return $result;
}

/**
 * 通知队列-塞入订单支付成功通知
 *
 * @param string $s_order_sn        订单编号
 * @param string $s_order_type      订单类型 njyy wxfw wxby dljy ptshp
 * @param array  $arr_extend
 *
 * @return int
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function queue_in_notice_order_pay_success($s_order_sn = '',$s_order_type = '',$arr_extend = []){
    $arr_data = [
      'order_sn'=>$s_order_sn,
      'notice_type'=>$s_order_type.'_pay_success',
    ];
    return predis_notice_queue_in($arr_data);

}

/**
 * 通知队列-塞入车辆子单检测结果通知 - 成功 失败 故障
 *
 * @param int    $n_order_id
 * @param int    $n_order_vehicle_id
 * @param string $check_type ok not_ok fail
 *
 * @return int
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function queue_in_notice_order_check($n_order_id = 0,$n_order_vehicle_id = 0,$check_type = ''){
    $arr_data = [
      'order_id'=>$n_order_id,
      'order_vehicle_id'=>$n_order_vehicle_id,
      'notice_type'=>'njyy_check_'.$check_type,
    ];
    return predis_notice_queue_in($arr_data);
}

/**
 * 通知队列-塞入退款成功通知
 *
 * @param string $s_order_sn
 * @param string $s_order_type
 * @param string $s_refund_sn
 * @param array  $arr_extend
 *
 * @return int
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
function queue_in_notice_order_refund($s_order_sn = '',$s_order_type = '',$s_refund_sn = '',$arr_extend = []){
    $arr_data = [
      'order_sn'=>$s_order_sn,
      'refund_sn'=>$s_refund_sn,
      'notice_type'=>$s_order_type.'_refund_success',
    ];
    return predis_notice_queue_in($arr_data);
}

/**************** 返还预约数量队列 ****************/

/*通知队列-塞入数据*/
function predis_appoint_num_queue_in($data){

    $json_data = json_encode($data);

    $table = 'appoint_num';
    $result = predis_queue_in($table,$json_data);
    return $result;
}

/*通知队列-取出数据*/
function predis_appoint_num_queue_out(){
    $table = 'appoint_num';
    $result = predis_queue_out($table,10);
    return $result;
}


/**************** 年检预约提醒队列 ****************/

/*通知队列-塞入数据*/
function predis_njyy_remind_queue_in($data){
    //$data['notice_type'] 通知消息类型 自己定义

    $json_data = json_encode($data);

    $table = 'njyy_remind';
    $result = predis_queue_in($table,$json_data);
    return $result;
}

/*通知队列-取出数据*/
function predis_njyy_remind_queue_out(){
    $table = 'njyy_remind';
    $result = predis_queue_out($table,10);
    return $result;
}

